package com.fernandomdo.ServiceAdministrator;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.fernandomdo.ServiceAdministrator.Publisher.PublisherListItem;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface.DatabaseConstants;

public class InfoPublisherFragment extends Fragment {
	public static final String TAG = "InfoPublisherFragment";
	
	private Context appContext;
	public static DatabaseInterface databaseInterface;
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		appContext = getActivity().getApplicationContext();
		databaseInterface = new DatabaseInterface(appContext);		
	}
	
	@Override
	public void onPause() {
		super.onPause();
		//databaseInterface.readableDB.close();
	}
	
	@Override
	public void onStop() {
		super.onStop();
		//databaseInterface.readableDB.close();
	}
	
	/**
	 * Called when the info needs to be updated to the currently selected item. Passing an object has some advantages
	 * <p>1) It allows us to have the information related to the list while also permitting us to access other info stored in a separate table
	 * @param item
	 */
	public void updateInfo(Object item) {
		if(item instanceof PublisherListItem) {
			TextView name 				= (TextView)getView().findViewById(R.id.publisher_name);	
			TextView currentTerritory	= (TextView)getView().findViewById(R.id.current_in_possesion);
			TextView lastTerritory 		= (TextView)getView().findViewById(R.id.last_in_possesion);
			TextView amountBorrowed		= (TextView)getView().findViewById(R.id.amount_borrowed_in_month);
			TextView lastCheckIn 		= (TextView)getView().findViewById(R.id.last_date_in);
			TextView lastCheckOut 		= (TextView)getView().findViewById(R.id.last_date_out);	
			
			Cursor publisherInfo = null;
			
			try {
				publisherInfo = new PublisherInfoLoader().execute(((PublisherListItem)item).id).get();
			}							
			catch (InterruptedException e) {
				e.printStackTrace();
			} 
			catch (ExecutionException e) {
				e.printStackTrace();
			}
			
			//update all of the TextViews
			PublisherInfoSorter infoSorter = new PublisherInfoSorter(publisherInfo);
	
			name.setText(((PublisherListItem)item).name);
			currentTerritory.setText(infoSorter.currentInPossesion);
			lastTerritory.setText(infoSorter.lastInPossesion);
			amountBorrowed.setText(infoSorter.amountBorrowed);
			lastCheckIn.setText(infoSorter.lastDateIn);
			lastCheckOut.setText(infoSorter.lastDateOut);
		}
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View parent = inflater.inflate(R.layout.publisher_info, container, false);
		return parent;
	}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//InfoSorter
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	private class PublisherInfoSorter {
		public String currentInPossesion;
		public String lastInPossesion;
		public String amountBorrowed;
		public String lastDateIn;
		public String lastDateOut;
		
		private Cursor publisherInfo;
		private ArrayList<Cursor> borrowedTerritories;
		private long idOfCurrent;
		private long idOfLast;
		
		public PublisherInfoSorter(Cursor publisherInfo) {
			this.publisherInfo = publisherInfo;
			sortInfo();
		}
		
		private void sortInfo() {
			if(publisherInfo.moveToFirst()) {
				idOfLast 	= publisherInfo.getLong(publisherInfo.getColumnIndex(DatabaseConstants.CURRENT_IN_POSSESION));
				idOfCurrent = publisherInfo.getLong(publisherInfo.getColumnIndex(DatabaseConstants.LAST_IN_POSSESION));
				
				try {
					borrowedTerritories = new TerritoryLoader().execute(idOfCurrent, idOfLast).get();
				} 
				catch (InterruptedException e) {
					e.printStackTrace();
				} 
				catch (ExecutionException e) {
					e.printStackTrace();
				}
				
				//Current Territory
				Cursor current = borrowedTerritories.get(0);
				if(current.moveToFirst()) {
					currentInPossesion = current.getString(current.getColumnIndex(DatabaseConstants.TERRITORY));    				
				}
				else {
					currentInPossesion = appContext.getResources().getString(R.string.no_territory);
				}
			
				//Current Territory
				Cursor last = borrowedTerritories.get(1);
				if(last.moveToFirst()) {
					lastInPossesion = last.getString(current.getColumnIndex(DatabaseConstants.TERRITORY));    				
				}
				else {
					lastInPossesion = appContext.getResources().getString(R.string.no_territory);
				}
			
				amountBorrowed 	= publisherInfo.getString(publisherInfo.getColumnIndex(DatabaseConstants.AMOUNT_BORROWED));
				lastDateIn		= publisherInfo.getString(publisherInfo.getColumnIndex(DatabaseConstants.LAST_DATE_IN));
				lastDateOut		= publisherInfo.getString(publisherInfo.getColumnIndex(DatabaseConstants.LAST_DATE_OUT));        	
			}
		}
	}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Async loaders to get the items from the database
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	* Simple Loader to retrieve the Publisher Info
	*/
	private class PublisherInfoLoader extends AsyncTask<Long, Integer, Cursor> {
		@Override
		protected Cursor doInBackground(Long... ids) {
			databaseInterface.readableDB = databaseInterface.databaseHelper.getReadableDatabase();
			Cursor cursor;
			
			final String[] FROM = { DatabaseConstants.PUBLISHER_ID, DatabaseConstants.CURRENT_IN_POSSESION, DatabaseConstants.LAST_IN_POSSESION, 
					DatabaseConstants.AMOUNT_BORROWED, DatabaseConstants.LAST_DATE_IN, DatabaseConstants.LAST_DATE_OUT};
			final String SELECTION = DatabaseConstants.PUBLISHER_ID + '=' + ids[0];
			cursor = databaseInterface.readableDB.query(DatabaseConstants.PUBLISHER_INFO_TABLE,  FROM, SELECTION, null, null, null, null);
			//return db.rawQuery("SELECT rowid _id,name,strftime('%s',started), strftime('%s', finished) FROM territory ORDER BY started DESC", new String[] {});
			return cursor;
	     }
	}
	
	/**
	* Simple Loader to retrieve the Territory Info
	*/
	private class TerritoryLoader extends AsyncTask<Long, Integer, ArrayList<Cursor>> {
		@Override
		protected ArrayList<Cursor> doInBackground(Long... ids) {
			databaseInterface.readableDB = databaseInterface.databaseHelper.getReadableDatabase();
			
			ArrayList<Cursor> cursors = new ArrayList<Cursor>();
			final String[] FROM = { BaseColumns._ID, DatabaseConstants.TERRITORY };
			String SELECTION = BaseColumns._ID + '=' + ids[0];
			
			for(int i=0; i<ids.length; i++) {
				SELECTION = BaseColumns._ID + '=' + ids[i];
				Cursor cursor = databaseInterface.readableDB.query(DatabaseConstants.TERRITORY_TABLE,  FROM, SELECTION, null, null, null, null);
				cursors.add(cursor);
			}
			//return db.rawQuery("SELECT rowid _id,name,strftime('%s',started), strftime('%s', finished) FROM territory ORDER BY started DESC", new String[] {});
			return cursors;
	     }
	}
}